package com.observatory.baapp;


import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.getcapacitor.BridgeActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;

import java.io.IOException;


import cn.jpush.android.api.JPushInterface;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BridgeActivity {
    private EventBus.EventListener eventListener;
//    private BroadcastReceiver jpushRegistrationReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
//                String regId = intent.getStringExtra(JPushInterface.EXTRA_REGISTRATION_ID);
//                if (regId != null && !regId.isEmpty()) {
//                    Log.d(TAG, "JPush Registration ID (Broadcast): " + regId);
//                    sendJPushTokenToServer(regId);
//                }
//            }
//        }
//    };

//    private static final String SERVER_URL = "https://your-server.com/api/save-token";
//    private final OkHttpClient httpClient = new OkHttpClient();
//    private String lastSavedToken = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        IntentFilter filter = new IntentFilter(JPushInterface.ACTION_REGISTRATION_ID);
//        registerReceiver(jpushRegistrationReceiver, filter);
//        //初始化JPush
        JPushInterface.setDebugMode(false); // 开发时开启调试
        JPushInterface.init(this);
        createNotificationChannel(); // 初始化通知渠道
        FirebaseApp.initializeApp(this);
        askNotificationPermission(); // 请求通知权限（Android 13+）
//        logRegToken(); // 触发获取令牌
        checkForBackgroundData();
        checkBatteryOptimization();
//        initJPushRegistration();
        if (getBridge() != null) {
            getBridge().eval("jsCode", null);
        }
        handleNavigation(getIntent());
        eventListener = new EventBus.EventListener() {
            @Override
            public void onEvent(String eventType) {
                if ("refreshEventList".equals(eventType)) {
                    runOnUiThread(() -> refreshEventList());
                }
            }
        };
        EventBus.getInstance().register(eventListener);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleNavigation(intent);
    }

    private void handleNavigation(Intent intent) {
        if (intent.hasExtra("NAVIGATE_TO")) {
            String route = intent.getStringExtra("NAVIGATE_TO");
            String triggerName = intent.getStringExtra("triggerName");

            if ("EventDetails".equals(route) && triggerName != null) {
                // 延迟执行确保 Bridge 初始化完成
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    if (getBridge() != null) {
                        String jsCode = String.format(
                                "window.handleNativeNavigation('eventdetails', { triggerName: '%s' })",
                                triggerName
                        );
                        getBridge().eval(jsCode, null);
                    } else {
                        Log.e(TAG, "Bridge is not initialized");
                    }
                }, 500); // 延迟 500ms 避免竞争条件
            }
        }
    }
    private static final String TAG = "MainActivity";

//    private void sendJPushTokenToServer(String registrationID) {
//        RequestBody formBody = new FormBody.Builder()
//                .add("jpushToken", registrationID)
//                .add("platform", "android")
//                .build();
//
//        Request request = new Request.Builder()
//                .url(SERVER_URL)
//                .post(formBody)
//                .build();
//
//        httpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                Log.e(TAG, "JPush Token上传失败: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Log.d(TAG, "JPush Token上传成功");
//                } else {
//                    Log.e(TAG, "JPush Token上传失败，状态码: " + response.code());
//                }
//            }
//        });
//    }

    private void checkForBackgroundData() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            Bundle extras = intent.getExtras();
            for (String key : extras.keySet()) {
                if (key.contains("jpush")) { // 处理JPush的附加数据
                    String value = extras.getString(key);
                    Log.d(TAG, "JPush Extra - " + key + ": " + value);
                    // 处理自定义业务逻辑
                }
            }
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "developer-default",
                    "JPUSH_CHANNEL",
                    NotificationManager.IMPORTANCE_HIGH
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

//    private void logRegToken() {
//        // [START log_reg_token]
//        FirebaseMessaging.getInstance().getToken()
//                .addOnCompleteListener(new OnCompleteListener<String>() {
//                    @Override
//                    public void onComplete(@NonNull Task<String> task) {
//                        if (!task.isSuccessful()) {
//                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
////                            Toast.makeText(MainActivity.this, "Failed to get FCM token!", Toast.LENGTH_LONG).show();
//                            return;
//                        }
//
//                        // Get new FCM registration token
//                        String token = task.getResult();
//                        if (!token.equals(lastSavedToken)) {
//                            sendTokenToServer(token);
//                            lastSavedToken = token;
//                        }
//                        // Log and toast
//                        String msg = "FCM Registration token: " + token;
//                        Log.d(TAG, msg);
////                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
//                    }
//                });
//        // [END log_reg_token]
//    }

//    private void sendTokenToServer(String token) {
//
//        RequestBody formBody = new FormBody.Builder()
//                .add("fcmToken", token)
//                .add("platform", "android")
//                .build();
//
//        Request request = new Request.Builder()
//                .url(SERVER_URL)
//                .post(formBody)
//                .build();
//
//        httpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                Log.e(TAG, "Token upload failed: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(@NonNull Call call, @NonNull Response response) {
//                if (response.isSuccessful()) {
//                    Log.d(TAG, "Token uploaded successfully");
//                } else {
//                    Log.e(TAG, "Token upload failed. Code: " + response.code());
//                }
//            }
//        });
//    }

//    private void checkForBackgroundData() {
//        // 检查是否有从后台通知启动应用的数据
//        if (getIntent().getExtras() != null) {
//            for (String key : getIntent().getExtras().keySet()) {
//                Object value = getIntent().getExtras().get(key);
//                Log.d(TAG, "Key: " + key + " Value: " + value);
//            }
//        }
//    }

    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    Log.d(TAG, "Notification permission granted");
                    // FCM SDK (and your app) can post notifications.
                } else {
                    Log.d(TAG, "Notification permission denied");
                    // TODO: Inform user that that your app will not show notifications.
                }
            });

    private void askNotificationPermission() {
        // This is only necessary for API level >= 33 (TIRAMISU)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
                    PackageManager.PERMISSION_GRANTED) {
                // 已有权限
            } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
                Toast.makeText(this, "Notifications are important for app functionality", Toast.LENGTH_LONG).show();
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            } else {
                // Directly ask for the permission
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }

    private void checkBatteryOptimization() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // 解除注册防止内存泄漏
        EventBus.getInstance().unregister(eventListener);
    }
    public void refreshEventList() {
        new Handler(Looper.getMainLooper()).post(() -> {
            Log.d("MainActivity", "执行 JS 刷新，Bridge 状态: " + (getBridge() != null));
            if (getBridge() != null) {
                String jsCode = "window.doRefresh && window.doRefresh();";
                getBridge().eval(jsCode, null);
            } else {
                Log.e(TAG, "Bridge is not initialized");
            }
        });
    }
}